//
//  AutoresController.m
//  Frases D Futbol
//
//  Created by Jose Luis Lopez on 22/05/11.
//  Copyright 2011 None. All rights reserved.
//

#import "AutoresController.h"
#import <AVFoundation/AVAudioPlayer.h>
#import "Mas.h"
#import "GAI.h"
#import "GAIDictionaryBuilder.h"



@implementation AutoresController

@synthesize listData, autor,banderaAudio, numAutor;

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{
    
    if ((self = [super initWithNibName:nil bundle:nibBundleOrNil])) {
        
        self.banderaAudio = YES;
        
        NSInteger entero;
        if ([nibNameOrNil isEqual:@"0"]) {
            entero = 1;
        } else if ([nibNameOrNil isEqual:@"1"]){
            entero = 2;            
        } else if ([nibNameOrNil isEqual:@"2"]){
            entero = 3;            
        } else if ([nibNameOrNil isEqual:@"3"]){
            entero = 4;            
        } else if ([nibNameOrNil isEqual:@"4"]){
            entero = 5;            
        } else if ([nibNameOrNil isEqual:@"5"]){
            entero = 6;            
        } else if ([nibNameOrNil isEqual:@"6"]){
            entero = 7;            
        } else if ([nibNameOrNil isEqual:@"7"]){
            entero = 8;            
        } else if ([nibNameOrNil isEqual:@"8"]){
            entero = 9;            
        } else if ([nibNameOrNil isEqual:@"9"]){
            entero = 10;            
        } else if ([nibNameOrNil isEqual:@"10"]){
            entero = 11;            
        } else if ([nibNameOrNil isEqual:@"11"]){
            entero = 12;            
        } else if ([nibNameOrNil isEqual:@"12"]){
            entero = 13;            
        } else if ([nibNameOrNil isEqual:@"13"]){
            entero = 14;            
        } else if ([nibNameOrNil isEqual:@"14"]){
            entero = 15;            
        } else if ([nibNameOrNil isEqual:@"15"]){
            entero = 16;            
        } else if ([nibNameOrNil isEqual:@"16"]){
            entero = 17;            
        } else {
            entero = 49;
        }
        
        self.numAutor = entero;
        Autor *aux = [[[Autor alloc] init:entero] retain];
        self.autor = aux;
        [[[[self.autor retain] retain] retain] retain];
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    self.screenName = [NSString stringWithFormat:@"Autor Screen: %@", self.autor.nombreAutor];
    
    [super viewDidLoad];
    
    UIButton *masButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
    [masButton addTarget:self action:@selector(mas:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:masButton];
    
    [self.navigationController.navigationBar.backItem setTitle:@"Back"];

    
    self.title = self.autor.nombreAutor;
    //[self.navigationController.navigationBar.topItem setTitle:self.autor.nombreAutor];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 44) style:UITableViewStylePlain];
    [tableView setDataSource:self];
    [tableView setDelegate:self];
    [self.view addSubview:tableView];
    
    NSMutableArray *aux = [NSMutableArray array];
    for (NSString *frase in self.autor.listaFrases) {
        [aux addObject:frase];
    }     
    
    NSArray *array = aux;
    /*
    [[NSArray alloc] initWithObjects:@"Luis Aragones", @"Van Gaal", @"Carlos Bilardo", @"Loco Gatti", @"Pep Guardiola", @"Berd Schuster", @"Valdano", @"Johan Cruiff", @"Raul Albiol", @"Sergio Ramos", @"Marcelino", @"Juanma Lillo", nil];
    */
    self.listData = array;
    

    
//    //  Aquí añadimos la barra superior
//    UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
//    navBar.barStyle = UIBarStyleBlackOpaque;    
//    
//    [self.view addSubview:navBar];
//    
//    //  Aquí agregamos la label a dicha barra
//    UILabel *labelBar = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
//    labelBar.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
//    labelBar.text = self.autor.nombreAutor;
//    labelBar.backgroundColor = [UIColor clearColor];
//    labelBar.textColor = [UIColor whiteColor];
//    labelBar.textAlignment = UITextAlignmentCenter;
//    [self.view addSubview:labelBar];
//    
//    //  Aquí agregamos el boton de atras
//    UIButton *boton = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 50, 44)];
//    [boton setTitle:@"Atras" forState:UIControlStateNormal];
//    [boton addTarget:self action:@selector(atras:) forControlEvents:UIControlEventTouchUpInside];
//    [boton setEnabled:YES];
//    
//    [self.view addSubview:boton];
    
    //  Añadimos la barra de abajo
//    UIToolbar *tBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 416, 320, 44)];
//    tBar.barStyle = UIBarStyleBlackOpaque;
//    [self.view addSubview:tBar];
    
//    UIButton *boton2 = [[UIButton alloc] initWithFrame:CGRectMake(0, 416, 320, 44)];
//    [boton2 setTitle:@"Más" forState:UIControlStateNormal];
//    [boton2 addTarget:self action:@selector(mas:) forControlEvents:UIControlEventTouchUpInside];
//    [boton2 setEnabled:YES];
//    [self.view addSubview:boton2];
   
    NSString *version = [[UIDevice currentDevice] systemVersion];
    int ver = [version intValue];
    if (ver < 7){
        //iOS 6 work
    }
    else{
        //iOS 7 related work
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
        tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark Table View Data Source Methods

//  El Table View tendrá tantas celdas como elementos nuestro array.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.listData count];
}

//  Se encarga de la visualizacion de la tabla.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    
    //  Para no perder los datos que queden fuera de la pantalla.
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
    if (cell == nil) 
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SimpleTableIdentifier] autorelease];
    
    //  Se cambia el texto de la label con el texto del array de la posicion correspondiente.
    NSUInteger row = [indexPath row];
    cell.textLabel.text = [self.listData objectAtIndex:row];
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [playButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
    [playButton setFrame:CGRectMake(0, 0, 35, 35)];
    [playButton setTag:indexPath.row];
    [playButton addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
    cell.accessoryView = playButton;
    
    return cell;    
}

-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    if (row < 0) {
        return nil;
    }
    return indexPath;
}

//  Aqui se pone el codigo que queremos que se ejecute cuando se toque una celda.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

-(void)buttonTapped:(UIButton *)sender {

    if (self.banderaAudio) {
        NSUInteger row = sender.tag;
        
        self.autor = [[Autor alloc] init:self.numAutor];
        NSArray *aux1 = self.autor.listaAudios;
        NSObject *obj = [aux1 objectAtIndex:row];
        NSString *cadena = (NSString *)obj;
        //NSString *cadena = [NSString stringWithFormat:@"%@", [aux1 objectAtIndex:row]];
        NSString *ruta = [[NSBundle mainBundle] pathForResource:cadena ofType:@"mp3"];
        NSLog(@"Ruta %@", ruta);
        AVAudioPlayer* elAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:ruta] error:NULL];
        elAudio.delegate = self;
        [elAudio play];
        self.banderaAudio = NO;
        
        float tiempo;
        tiempo = [[self.autor.listaDuraciones objectAtIndex:row] floatValue];
        [NSTimer scheduledTimerWithTimeInterval:tiempo target:self selector:@selector(activaBandera) userInfo:nil repeats:NO];
        
        [[[GAI sharedInstance] defaultTracker] send:
         [[GAIDictionaryBuilder createEventWithCategory:autor     // Event category (required)
                                                 action:@"button_press"  // Event action (required)
                                                  label:self.autor.listaFrases          // Event label
                                                  value:nil] build]];
    }
}
-(void)atras:(id)sender
{
    Frases_D_FutbolViewController * controller = [[Frases_D_FutbolViewController alloc] initWithNibName:nil bundle:nil];
    controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:controller animated:YES];
}

-(void)activaBandera 
{
    self.banderaAudio = YES;
}

-(void)mas:(id)sender
{
    Mas * controller = [[Mas alloc] initWithNibName:nil bundle:nil];
    controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
//    [self presentModalViewController:controller animated:YES];
    
    UINavigationController *navCont = [[UINavigationController alloc] initWithRootViewController:controller];
    [self presentModalViewController:navCont animated:YES];
}



@end
